﻿using System.Net;

namespace LvcChong
{
    public partial class FormLogin : Form
    {
        public CookieCollection CookieCollection { get; private set; }

        public FormLogin()
        {
            InitializeComponent();
        }

        private async void FormLogin_Load(object sender, EventArgs e)
        {
            await webView21.EnsureCoreWebView2Async();
            webView21.CoreWebView2.NavigationCompleted += CoreWebView2_NavigationCompleted;
            picCode.Image = GlobalContext.DataProvider.GetCode();
        }

        private void CoreWebView2_NavigationCompleted(object? sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
        {
            this.Enabled = true;
            this.Hide();
            new FormMain().Show();
        }

        private void picCode_Click(object sender, EventArgs e)
        {
            picCode.Image = GlobalContext.DataProvider.GetCode();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
#if DEBUG
            txtUserName.Text = "15904856855";
            txtPassword.Text = "Hmjt@123.com";
#endif

            if (string.IsNullOrWhiteSpace(txtUserName.Text))
            {
                MessageBox.Show("请输入用户名");
                return;
            }
            if (string.IsNullOrWhiteSpace(txtPassword.Text))
            {
                MessageBox.Show("请输入密码");
                return;
            }
            if (string.IsNullOrWhiteSpace(txtUserName.Text))
            {
                MessageBox.Show("请输入用户名");
                return;
            }
            this.Enabled = false;
            try
            {
                GlobalContext.DataProvider.Login(txtUserName.Text, txtPassword.Text, txtCode.Text);
                PrepareToNavigateHome();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                this.Enabled = true;
            }
        }

        private void PrepareToNavigateHome(string path = "/")
        {
            foreach (Cookie cookie in GlobalContext.DataProvider.CookieCollection)
            {
                var cookieObj = webView21.CoreWebView2.CookieManager.CreateCookie(cookie.Name, cookie.Value, cookie.Domain, cookie.Path);
                webView21.CoreWebView2.CookieManager.AddOrUpdateCookie(cookieObj);
            }

            webView21.CoreWebView2.Navigate(GlobalContext.ServerHost + path);
        }

        private void FormLogin_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }
    }
}
